import 'package:t3_data_service/biz_data_source/common_address/common_address_service.dart';
import 'package:t3_data_service/t3_data_service.dart';
import 'package:t3_foundation/t3_foundation.dart';
import 'package:uikit/uikit.dart';

import '../model/section_model.dart';
import '../widget/entry_widget/entry_item.dart';

class POISearchPageViewModel extends ViewModel {
  var entryItems = <EntryItem>[].obs;
  var sections = <POIListSection>[].obs;

  var hasSearched = false;
  String? currentKeyword;

  bool get showEmpty {
    return sections.value.isEmpty && hasSearched && (currentKeyword != null) && (currentKeyword ?? '').isNotEmpty;
  }

  bool get showEntryItems {
    var hasSearchResult = (currentKeyword ?? '').isNotEmpty && sections.value.isNotEmpty;
    return entryItems.value.isNotEmpty && !showEmpty && !hasSearchResult;
  }

  updateSections(List<POIListSection> list, String? keyword) {
    currentKeyword = keyword;
    sections.value = list;
    hasSearched = true;
  }

  CommonAddress? home;
  CommonAddress? company;

  updateEntries(List<EntryItem> items) {
   entryItems.value = items;
  }

  modifyEntry(EntryItemType type, CommonAddress commonAddress) {
    if (type == EntryItemType.home) {
      home = commonAddress;
    } else if (type == EntryItemType.company) {
      company = commonAddress;
    }

    var items = entryItems.value;
    List<EntryItem> newItems = [];
    for (var item in items) {
      if (item.type == type) {
        var newOne = EntryItem(
          iconName: item.iconName,
          title: item.title,
          type: type,
          subtitle: commonAddress.addressTitle ?? (type == EntryItemType.home ? "设置家地址" : "设置公司地址"),
          detailIconName: item.detailIconName,
          showDividerLine: item.showDividerLine,
          clicked: item.clicked,
          clickedDetail: item.clickedDetail,
        );
        newItems.add(newOne);
      } else {
        newItems.add(item);
      }
    }
    entryItems.value = newItems;
  }

  deleteEntry(EntryItemType type) {
    if (type == EntryItemType.home) {
      home = null;
    } else if (type == EntryItemType.company) {
      company = null;
    }
    var items = entryItems.value;
    List<EntryItem> newItems = [];
    for (var item in items) {
      if (item.type == type) {
        var newOne = EntryItem(
          iconName: item.iconName,
          title: item.title,
          type: type,
          subtitle: type == EntryItemType.home ? "设置家地址" : "设置公司地址",
          detailIconName: item.detailIconName,
          showDividerLine: item.showDividerLine,
          clicked: item.clicked,
          clickedDetail: item.clickedDetail,
        );
        newItems.add(newOne);
      } else {
        newItems.add(item);
      }
    }
    entryItems.value = newItems;
  }
}